package arrays;

/**
 * @author pengfei.hpf
 * @date 2020/3/4
 * @verdion 1.0.0
 */
public class NumMatrix {
    private int[][] rowSums;
    private int[][] allSums;
    int rlen = 0;
    int clen = 0;
    public NumMatrix(int[][] matrix) {
        rlen = matrix.length;
        if(rlen > 0){
            clen = matrix[0].length;
            if(clen > 0){
                rowSums = new int[rlen][clen];
                allSums = new int[rlen][clen];
                for(int i = 0; i < rlen; i ++){
                    for(int j = 0; j < clen; j ++){
                        if(j == 0){
                            rowSums[i][j] = matrix[i][j];
                        } else {
                            rowSums[i][j] = rowSums[i][j - 1] + matrix[i][j];
                        }
                    }
                }

                for(int i = 0; i < clen; i ++){
                    for(int j = 1; j < rlen; j ++){
                        allSums[i][j] = allSums[i-1][j];
                    }
                }
            }
        }


    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        if(row1 <0 || col1 < 0 || row1 > row2 || col1 > col2 || col2 > clen || row2 > rlen){
            return 0;
        }
        sum = allSums[row2][col2] - allSums[row1][col1];
        return sum;
    }

    public static void main(String[] args){
        int[][] m = new int[1][0];
    }
}
